package com.logic.modular.game.achievement;

import com.comment.exception.ServiceException;
import com.comment.pojo.domain.bag.BagItem;
import com.logic.comment.util.XsRedisUtils;
import com.logic.modular.game.player.bag.service.BagItemServiceImpl;
import com.logic.modular.game.player.bag.service.PlayerPropType1ServiceImpl;
import com.logic.modular.game.statistical.domain.PlayerStatisticalPool;
import com.logic.modular.game.statistical.service.impl.PlayerStatisticalPoolServiceImpl;
import com.logic.modular.gameCore.cultivate.achievement.domain.CoreAchievementAward;
import com.logic.modular.gameCore.cultivate.achievement.service.impl.CoreAchievementAwardServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AchievementServiceImpl {
    @Resource
    private PlayerStatisticalPoolServiceImpl playerStatisticalPoolService;
    @Resource
    private PlayerPropType1ServiceImpl playerPropType1Service;
    @Resource
    private BagItemServiceImpl bagItemServiceImpl;
    @Resource
    private XsRedisUtils xsRedisUtils;


    public List<CoreAchievementAward> list() {
        return CoreAchievementAwardServiceImpl.listCache();
    }

    public PlayerStatisticalPool viewProgress(Long playerId) {
        return playerStatisticalPoolService.obtain(playerId);
    }


    @Transactional
    public boolean gradeClaimRewards(Long playerId, Long id) {
        List<Long> toList = xsRedisUtils.getToList(String.format("achievement:%d", playerId), Long.class);
        if (toList == null) {
            toList = new ArrayList<>();
        }
        if (toList.contains(id)) {
            throw new ServiceException("已领取");
        }
        CoreAchievementAward cache = CoreAchievementAwardServiceImpl.getCache(id);
        // 查看
        Long points = cache.getPoints();
        BagItem bagItem = playerPropType1Service.viewCurrency(playerId, 7L);
        if (bagItem.num.compareTo(BigDecimal.valueOf(points)) < 0) {
            String log = String.format("成就点不足,还差%d", points - bagItem.num.intValue());
            throw new ServiceException(log);
        }
        Map<Long, Long> award1 = cache.getAward1();
        award1.forEach((awardId, value) -> bagItemServiceImpl.obtainBagItem(playerId, awardId, new BigDecimal(value)));
        toList.add(id);
        xsRedisUtils.set(String.format("achievement:%d", playerId), toList);
        return true;
    }

    public List<Long> viewReceivedAchievementLevelRewards(Long playerId) {
        return xsRedisUtils.getToList(String.format("achievement:%d", playerId), Long.class);
    }
}

